import { create, remove, update, query, getUserInfo, getVaildCode, showShade, getFlag, getQRCode } from '../services/User';
import { parse } from 'qs';
import Loading from '~/components/Loading';
import 'whatwg-fetch';
import { message, Modal } from 'antd';
import smileImg from '../assets/smile1.png';
import { config, canShareConfig } from '../wx/wechat';
import { getQueryStringByName } from '~/utils/common';
import { url } from '~/config';
export default {

  namespace: 'users',
  state: {
    phone: '',
    role: '',
    name: '',
    shopName:'',
    shopNO: '',
    headImg: smileImg,
    returnErrText: '',
    modalVisiblen: false,
    hide: false,
    canClose: false,
    showShade: false,
    qrcodeurl:'',
    showKnow: false,
    activitys:[],
  },

  subscriptions: {
    setup({ dispatch, history }) {

      let userphone = getQueryStringByName('phone');
      let headImg = getQueryStringByName('headimg');
      function getQRCode(phone){
        // dispatch({
        //   type: 'showShade',
        //   payload: { actId: 1 },
        // })
        return new Promise((resolve,reject) =>{
          dispatch({
            type:'getQRCode',
            payload:{phone,},
            resolve,
            reject,
          })
        })
      };
      function getQRCodeSuccess(payload){
        dispatch({
          type:'getQRCodeSuccess',
          payload,
        })
      };
      Loading.show();
      function getUserPhone(userphone){
        canShareConfig(userphone, headImg);
        getQRCode(userphone).then((data) => {
          Loading.hide();
          const {url,
            clerk,
          } = data.data.body;
          const {  clerkPosition,
            clerkName,
            storeName,} =clerk;
          getQRCodeSuccess({qrcodeurl:url,
            headImg,
            phone:userphone,
            role:clerkPosition === 1 ? '店员' : '店长',
            name:clerkName,
            shopName:storeName,
          });
        })
        .catch((err) => {
          Loading.hide();
          Modal.error({
             title: '提示',
             content: err.errorMsg || '页面已失效',
             onOk: () => {

             },
          });
        });
      }
      function getCode(){
        console.log('getCode')
        const code = getQueryStringByName('code');
        const state = getQueryStringByName('state');
        if(state && code) {
          new Promise((resolve,reject) => {
            dispatch({
              type: 'query',
              payload: { state, code },
              resolve,
              reject
            });
          })
          .then((data) => {
            headImg = data.data.body.headUrl;
            const activitys = data.data.body.activity || [];
            getQRCodeSuccess({headImg, activitys});
          })
          .catch((err) => {
            Loading.hide();
            window.location.href = url;//重新获取一个code
          });
        } else {
          window.location.href = url;
        }
      }
      function getUserName(){
        new Promise((resolve,reject) => {
          dispatch({
            type: 'query',
            payload: { state: __PRO__ ? 'b4e68e3ec8f511e6a96f00163e0a07e1' : 'c719566bc35d11e6bd5d0050569f4cfd' , code: '', authCode: window.sessionStorage.authCode },
            resolve,
            reject
          });
        })
        .then((data) => {
          const  phone = data.data.body.clerk.clerkPhone;
          headImg = data.data.body.headUrl;
          const activitys = data.data.body.activity;
          getQRCodeSuccess({headImg, activitys});
        })
        .catch((err) => {
          Loading.hide();
          // Modal.error({
          //    title: '出错啦',
          //    content: err.err.message || err.err.errorMsg,
          //    onOk: () => {
                // const url = __PRO__ ? 'http://weixin.4000916916.com/wechatBH/oauth2?state=b4e68e3ec8f511e6a96f00163e0a07e1'
                // : 'http://wx-test.by-health.com/wechatBH/oauth2?state=c719566bc35d11e6bd5d0050569f4cfd';
                window.location.href = url;//重新获取一个code
          //    },
          // });
        });
      }
      if (userphone) {
        getUserPhone(userphone);
      // } else if (window.sessionStorage.authCode) {
      //   getUserName()
      } else {
        getCode();
      }
      if(!__DEV__){
      history.listen(location => {
        if (location.pathname === '/') {
          config();
        } else if (location.pathname === '/demo') {
          config();
        } else if (location.pathname === '/memberSelf') {
          if(!userphone)  {
          dispatch({
            type:'configWechat',
          })
          }
        }
      });}
    },
  },

  effects: {
    *configWechat({ }, { call, put ,select}){
      const {phone,headImg}= yield select(({ users }) => users);
      canShareConfig(phone, headImg);
    },
    *query({ payload, resolve, reject }, { call, put }) {
      const data = yield call(query, payload);
      if(data.data) {
        const datas = data.data;
        if (datas.status === '0') {
          // alert(datas.body.authCode);
          if(datas.body.type === 1) {
            Modal.warning({
               title: '提示信息',
               content: '门店处于关闭状态,详情可致电4000916916咨询',
               onOk: () => {
               },
            });
          }
          if(datas.body.type === 2) {
            Modal.warning({
               title: '提示信息',
               content: '会员店请登录营养管家app操作',
               onOk: () => {
               },
            });
          }
          if(datas.body.type === 3) {
            Modal.warning({
               title: '提示信息',
               content: '您的账户存在异常,详情可致电4000916916咨询',
               onOk: () => {
               },
            });
          }
          if(datas.body.type === 4) {
            Modal.warning({
               title: '提示信息',
               content: '您的手机号码属于汤臣倍健内部人员,无法参加本次活动,详情可致电4000916916咨询',
               onOk: () => {
               },
            });
          }
          window.sessionStorage.authCode = datas.body.authCode;
          if(!datas.body.clerk) {
            yield put({
              type: 'querySuccess',
              payload: {
                modalVisible: true,
              },
            });
          } else {
            const Data = datas.body.clerk;
            yield put({
              type: 'querySuccess',
              payload: {
                phone: Data.clerkPhone,
                role: Data.clerkPosition === 1 ? '店员' : '店长',
                name: Data.clerkName,
                shopName: Data.storeName,
                modalVisible: false,
                shopNO: Data.storeNo,
                headImg: datas.body.headUrl ? datas.body.headUrl : smileImg,
                activitys: datas.body.activity || [],
              },
            });
          }
        }
        Loading.hide();
        resolve(data);
      } else {
        Loading.hide();
        reject(data);
      }
    },
    *update({ payload, resolve, reject }, { select, call, put }) {
        Loading.show();
        const data = yield call(update, {
          name: payload.name,
          phone: payload.phone,
          storeNo: payload.shopper,
          validateCode: payload.validateCode,
          type: 1,
          authCode: window.sessionStorage.authCode,
        });
        if (data.data) {
          resolve(data)
        } else {
          Loading.hide();
          reject(data)
        }
    },
    *showShade({ payload, resolve, reject}, { select, call, put}) {
      const activeStatus = yield call(showShade, payload);
      if (activeStatus.data.body.actProgress === 98) {
        yield put({
          type: 'showOrHide',
          payload: {showShade: false},
        })
      } else {
        yield put({
          type: 'showOrHide',
          payload: {showShade: true},
        })
      }
    },
    *getVaildCode({ payload, resolve, reject }, { call, put }) {
      const data = yield call(getVaildCode, payload);
      if(data.data) {
        resolve(data)
      } else {
        reject(data)
      }
    },
    *getFlag({ payload, resolve, reject }, { call, put }) {

      const data = yield call(getFlag, payload);
      if (data.data) {
        resolve(data);
      } else {
        reject(data);
      }
    },
    *getQRCode({ payload, resolve, reject }, { call, put }) {
      const data = yield call(getQRCode, payload);
      if (data.data) {
        resolve(data);
      } else {
        reject(data);
      }
    },
  },

  reducers: {
    updateSuccess(state, action) {
      const updateUser = action.payload;
      Loading.hide();
      return { ...state, ...updateUser, modalVisible: false };
    },
    updateFail(state, action) {
      Loading.hide();
      return { ...state, ...action.payload };
    },
    querySuccess(state, action) {
      return { ...state, ...action.payload, loading: false };
    },
    showModal(state, action) {
      return { ...state, ...action.payload, modalVisible: true, hide: true, canClose: true, };
    },
    hideModal(state) {
      return { ...state, modalVisible: false };
    },
    // showShade(state){
    //   return {...state, showShade: true};
    // },
    // hideShade(state){
    //   return {...state, showShade: false};
    // },
    showOrHide(state, action) {
      return {...state, ...action.payload}
    },
    getQRCodeSuccess(state, action) {
      return {...state, ...action.payload}
    },
    changeMemerSelf(state, action) {
      return {...state, showKnow: true}
    }
  },
};
